from django.contrib.auth.backends import ModelBackend
import re
from .models import User
from itsdangerous import TimedJSONWebSignatureSerializer as TJSSerializer
from django.conf import settings

def jwt_response_payload_handler(token, user=None, request=None):
    """重写此方法补充返回登录后的响应数据"""
    print('xxxx')
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }


def get_user_by_account(account):
    """
    根据帐号获取user对象
    :param account: 账号，可以是用户名，也可以是手机号
    :return: User对象 或者 None
    """
    try:
        if re.match('^1[3-9]\d{9}$', account):
            # 帐号为手机号
            user = User.objects.get(mobile=account)
        else:
            # 帐号为用户名
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user

class UsernameMobileAuthBackend(ModelBackend):
    """给django认证后端类定义子类 改写查询user逻辑,实现多账号登录"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        # 根据前端传入的account 动态去查询user
        user = get_user_by_account(username)
        # 校验密码是否正确
        if user and user.check_password(password):
            return user


#
# def generate_email_verify_url(user):
#     """生成邮箱激活url"""
#     serializer = TJSSerializer(settings.SECRET_KEY,24 *60 *60)
#     data ={'user_id':user.id ,'email':user.email}
#     token =serializer.dump(data).decode()
#     # 返回激活url
#     return  "http://www.meiduo.site:8080/success_verify_email.html?token=%s" % token